package top.jnaw.test.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import java.util.List;
import lzj.tools.Https;
import lzj.tools.StringUtils;
import top.jnaw.test.model.Users;
import top.jnaw.test.service.DeptService;
import top.jnaw.test.service.UserService;
import top.jnaw.test.util.plugin.Shiros;

public class UserController extends Controller {

  /**
   * 登出
   */
//  @RequiresAuthentication
  public void logout() {
    if (Shiros.isAuthc()) {
      Shiros.logout();
    }
    renderJson(Https.success("退出成功", ""));
  }

  /**
   * 里面有更新用户角色权限缓存的接口
   * 也可以在shiro.ini中配置是否使用缓存

   public void setRoole() {
   Shiros.clearCached("admin");
   renderHtml("清空授权");
   }
   */

  /**
   * 登录加获取用户信息
   */

  public void getUserInfo() {
    final String username = getPara("username", "").trim();
    final String password = getPara("password", "").trim();
    boolean result = false;
    if (StrKit.notBlank(username, password)) {
      result = Shiros.login(username, password);
    }
    if (result) {
      //返回信息
      Record users = UserService.getUserInfo2(username);
      renderJson(Https.success("登录成功", users));
    } else {
      renderJson(Https.failure("用户名或密码错误", ""));
    }

  }

  public void add() {
    final String username = getPara("username", "").trim();
    final String password = getPara("password", "").trim();
    final String name = getPara("name", "").trim();
    boolean result = false;
    if (StrKit.notBlank(username, password)) {
      result = Shiros.addUser(username, password);
    }

    if (result) {
      //返回信息
      Record users = UserService.getUserInfo2(username);
      renderJson(Https.success("注册成功", users));
    } else {
      renderJson(Https.failure("用户名或密码错误", ""));
    }

  }

  //  @CacheName("hrl")
  public void getUsersList() {
    final String username = getPara("username", "").trim();
    final String name = getPara("name", "").trim();
    boolean result = false;

    List<Users> list = UserService.getUserList();
    renderJson(list);
  }

  /**
   * 查看所有用户，包括子部门的(分页)
   */
  public void getUserListByDept() {
    String name = getPara("name", "").trim();
//    String phone = getPara("phone", "").trim();
    String depid = getPara("deptid", "1");
//    String rolename = getPara("role", "").trim();
    final int page = getParaToInt("page", 1);
    final int size = getParaToInt("size", 15);
    int type = getParaToInt("type", 1);//type=0包含子级的人员，1则是本级的人员
//    int state = getParaToInt("state", 1);//用户状态，0已停用，1正常

    //格式调整
    depid = StringUtils.ReadIds(depid);

    Page<Record> userList = null;

    if (type == 0) {
      userList = DeptService.getUserString(depid, name, 1, page, size);
    } else {
      userList = DeptService.getDeparmentPeople(depid, name, 1, page, size);
    }
    renderJson(Https.success("查询成功", userList));
  }


}
